<template>
  <div class="container">
    <!-- 顶部导航栏 -->
    <GeneralTopBar :showPosition="false"/>
    <main class="margin-20per">
      <div class="main-header">
        <el-page-header @back="$router.back()" content="新增职位"></el-page-header>
      </div>
      <div class="main-content">
        <!-- el-form坑：多个同名表单验证只回调最后一个表单的检验结果，所以valid结果永为true
             解决：放在一个表单里就行
         -->
        <el-form :model="jobForm" :rules="jobFormRules" ref="jobForm">
          <div class="post-wrapper">
            <h2>职位基本信息</h2>
            <div class="content">
  <!--            <el-form :model="jobForm" :rules="jobFormRules" ref="jobForm">-->
                <el-form-item class="left-form-item" label="职位名称" prop="title" >
                  <el-input v-model="jobForm.title"></el-input>
                </el-form-item>
                <el-form-item class="right-form-item" label="薪资待遇" prop="expectedSalaryId">
                    <el-select v-model="jobForm.expectedSalary.id" placeholder="请选择薪资待遇">
                        <el-option v-for="item in this.expectedSalaryList"
                                   :key="item.id"
                                   :label="item.title"
                                   :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="left-form-item" label="所属行业" prop="positionId" >
                    <el-cascader
                            v-model="value"
                            :options="options"
                            @change="handleChange"
                            style="width: 100%"
                    >
                    </el-cascader>
                </el-form-item>
                <el-form-item class="right-form-item" label="要求性别（默认不限）" prop="askSex">
                    <el-radio v-model="jobForm.askSex" label="不限">不限</el-radio>
                    <el-radio v-model="jobForm.askSex" label="男生">男生</el-radio>
                    <el-radio v-model="jobForm.askSex" label="女生">女生</el-radio>
                </el-form-item>
                <el-form-item class="left-form-item" label="工作经验" prop="workExperienceId">
                  <el-select v-model="jobForm.workExperience.id" placeholder="请选择工作经验">
                    <el-option
                        v-for="item in this.workExperienceList"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item class="right-form-item" label="学历要求" prop="recruitmentEducationId">
                  <el-select v-model="jobForm.recruitmentEducation.id" placeholder="请选择学历">
                    <el-option
                        v-for="item in this.recruitmentEducationList"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item class="left-form-item" label="招聘人数（选填）" prop="recruitingNumbers">
                    <el-input v-model="jobForm.recruitingNumbers"></el-input>
                </el-form-item>
                <el-form-item class="right-form-item" label="工作类型（默认全职）" prop="natureWorkId">
                    <el-select v-model="jobForm.natureWork.id" placeholder="请选择工作类型">
                        <el-option
                                v-for="item in this.natureWorkList"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id">
                        </el-option>
                    </el-select>
<!--                  <el-radio v-model="jobForm.natureWork" label="全职">全职</el-radio>-->
<!--                  <el-radio v-model="jobForm.natureWork" label="兼职">兼职</el-radio>-->
<!--                  <el-radio v-model="jobForm.natureWork" label="实习">实习</el-radio> -->
                </el-form-item>
  <!--            </el-form>-->
            </div>
          </div>
          <div class="post-wrapper">
            <h2>工作地点</h2>
            <div class="content">
                <el-form-item class="left-form-item" label="所属省" prop="province.id" style="width: 300px">
                    <el-select v-model="jobForm.province.id" placeholder="请选择" @change="provinceChange(jobForm.province.id)" style="width: 250px" >
                        <el-option
                                v-for="item in this.provinces"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id"
                        >
                            <span style="float: left">{{ item.title }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="left-form-item" label="所属市" prop="city.id" style="width: 300px">
                    <el-select v-model="jobForm.city.id" placeholder="请选择" @change="cityChange(jobForm.city.id)" style="width: 250px">
                        <el-option
                                v-for="item in this.citis"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id"
                        >
                            <span style="float: left">{{ item.title }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="left-form-item" label="所属区" prop="addressId" style="width: 300px">
                    <el-select v-model="jobForm.address.id" placeholder="请选择" style="width: 250px">
                        <el-option
                                v-for="item in this.areaList"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id"
                        >
                            <span style="float: left">{{ item.title }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="详细地址" prop="addressContent">
                    <el-input v-model="jobForm.addressContent"></el-input>
                </el-form-item>
  <!--            </el-form>-->
            </div>
          </div>
          <div class="post-wrapper">
            <h2>职位描述</h2>
            <div class="content">
  <!--            <el-form :model="jobForm" :rules="jobFormRules" ref="jobForm">-->
<!--                <el-form-item label="工作内容" prop="job_description">-->
<!--                  <Editor :placeholder="'请描述工作内容，建议使用短句并分条列出，如下<br>1. .... <br>2. .... <br>3. ....'"-->
<!--                          :content.sync="jobForm.job_description"-->
<!--                          :menus="['list']"-->
<!--                          :showFullScreen="false"-->
<!--                          :key="key"/>-->
<!--                </el-form-item>-->
                <el-form-item label="岗位要求" prop="jobDescriptionId">
                  <Editor :placeholder="'请描述岗位要求，建议使用短句并分条列出，如下<br>1. .... <br>2. .... <br>3. ....'"
                          :content.sync="jobForm.jobDescription"
                          :menus="['list']"
                          :showFullScreen="false"
                          :key="key"/>
                </el-form-item>
                <el-form-item label="职位福利（选填）" prop="jobWelfareLabelBasicsTitles">
                    <el-checkbox-group v-model="jobForm.jobWelfareLabelBasicsTitles" >
                        <el-checkbox :label="item.title" border v-for="item in welfareLabelBasicsList"
                            :key="item.id"
                            :value="item.id"
                        >{{item.title}}

                        </el-checkbox>
                    </el-checkbox-group>
<!--                    <el-checkbox-group v-model="checkList">-->
<!--                        <el-checkbox-->
<!--                                v-for="item in welfareLabelBasicsList"-->
<!--                                :key="item.id"-->
<!--                                :value="item.id"-->
<!--                        >-->
<!--                            {{ item.title }}-->
<!--                        </el-checkbox>-->
<!--                    </el-checkbox-group>-->

<!--                    <el-checkbox-group v-model="jobForm.jobWelfareLabelBasicsList">
                        <el-checkbox v-for="(welfareLabelBasic) in this.welfareLabelBasicsList" :label="title.title" :key="welfareLabelBasic.id">
                            {{welfareLabelBasic.title}}
                        </el-checkbox>
                    </el-checkbox-group>-->
                </el-form-item>
  <!--            </el-form>-->
            </div>
          </div>
<!--          <div class="post-wrapper">-->
<!--            <h2>其他信息</h2>-->
<!--            <div class="content">-->
<!--  &lt;!&ndash;            <el-form :model="jobForm" :rules="jobFormRules" ref="jobForm">&ndash;&gt;-->
<!--                <el-form-item label="附加信息（选填）" prop="attached_info">-->
<!--                  <Editor :placeholder="'请描述附加信息，建议使用短句并分条列出，例如：<br>工作时间：....<br>特殊技能加分项：....'"-->
<!--                          :content.sync="jobForm.attached_info"-->
<!--                          :menus="['list']"-->
<!--                          :showFullScreen="false"-->
<!--                          :key="key"/>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="面试信息（选填）" prop="interview_info">-->
<!--                  <Editor :placeholder="'请描述面试信息，建议使用短句并分条列出，例如：<br>面试方式：...<br>面试轮数：...<br>面试时间：...<br>是否自带简历：...'"-->
<!--                          :content.sync="jobForm.interview_info"-->
<!--                          :menus="['list']"-->
<!--                          :showFullScreen="false"-->
<!--                          :key="key"/>-->
<!--                </el-form-item>-->
<!--  &lt;!&ndash;            </el-form>&ndash;&gt;-->
<!--            </div>-->
<!--          </div>-->
          <div class="handle-btn">
            <el-button type="text" class="draft-btn"
                       @click="submitForm('jobForm','1')"
            >存入草稿箱
            </el-button>
            <el-button class="preview-btn" @click="submitForm('jobForm','0',true)"
            >预览
            </el-button>
            <el-button type="primary" class="add-btn"
                       @click="submitForm('jobForm','0')"
            >发布
            </el-button>
          </div>
        </el-form>
      </div>
    </main>
    <!-- 底部信息栏 -->
    <GeneralFooter/>

    <PreviewPicture v-if="previewVisible" :preview="previewVisible" @update:preview="previewOver"
                    :job_id="jobForm.id" :isProfession="true"/>
  </div>
</template>

<script>
import GeneralTopBar from "../../../components/GeneralTopBar";
import GeneralFooter from "../../../components/GeneralFooter";
// import AddTag from "@/components/AddTag";
// import CityDialog from "@/components/CityDialog";
// import Address from "@/components/Address";
import Editor from "@/components/Editor";
import PreviewPicture from "@/components/PreviewPicture";

export default {
  name: "PostJob",
  components: {
    GeneralTopBar,
    GeneralFooter,
    // AddTag,
    // CityDialog,
    // Address,
    Editor,
    PreviewPicture
  },
  // computed: {
  //   tagTransform: function() {
  //     const length = this.jobForm.storageJobTag.length;
  //     let str = "";
  //     if (length !== 0) {
  //       for (const [key, value] of Object.entries(this.jobForm.storageJobTag)) {
  //         str += key !== (length-1).toString() ? value + "," : value;
  //       }
  //     }
  //     return str;
  //   }
  // },
  data() {
    return {
      checkboxGroup2: [],
      value:[],
      options:[],
      addressList:[],
      checkList:[],
      // prop传值后，当prop被修改，子组件无法及时更新，用key值引发子组件刷新
      key: 0,
      provinces:[],
      citis:[],
      areaList:[],
      welfareLabelBasicsList:[],
      jobForm: {
        id: "",
        title:'',
        jobWelfareLabelBasicsTitles:[],
        expectedSalaryId:'',
        expectedSalaryList:[],
        expectedSalary:{},
        askSex:"不限",
        position:{},
        workExperienceId:'',
        workExperience:{},
        addressContent:"",
        natureWork:{},
        recruitingNumbers:"",
        // jobWelfareLabelBasicsList:{},
        publisherId: this.$store.state.login_id,
        positionType:{},
        industry: {},
        province:{},
        city:{},
        address:{},
        addressId:'',
        jobDescription:"",
        // tag前端临时存储
        // storageJobTag: [],
        // 后台接收的job_tag数据为String类型，前端转换
        // job_tag: "",
        recruitmentEducation: {},

      },
      jobFormRules: {
        job_duty: [
          {required: true, message: "请输入职位名称", trigger: ["blur", "change"]}
        ],
        job_industry: [
          {required: true, message: "请选择所属行业类型", trigger: ["blur", "change"]}
        ],
        job_salary: [
          {required: true, message: "请给出职位薪资", trigger: ["blur", "change"]}
        ],
        job_year: [
          {required: true, message: "请选择工作经验", trigger: ["blur", "change"]}
        ],
        education: [
          {required: true, message: "请选择学历要求", trigger: ["blur", "change"]}
        ],
        job_description: [
          {required: true, message: "工作内容不能为空", trigger: ["blur", "change"]}
        ],
        job_requirement: [
          {required: true, message: "岗位要求不能为空", trigger: ["blur", "change"]}
        ],
        office_address: [
          {required: true, message: "请输入工作详细地址", trigger: ["blur", "change"]}
        ]
      },
      industryList: [],
      workExperienceList:[],
      expectedSalaryList:[],
      recruitmentEducationList:[],
      natureWorkList: [],
      min_salary: undefined,
      max_salary: undefined,
      extra_salary: undefined,

      dialogVisible: false,
      previewVisible: false
    }
  },
  async created() {
    this.$store.commit("setLogin");
      this.$axios.all([this.industryData(),
          this.workExperienceData(),
          this.recruitmentEducationData(),
          this.natureWorkData(),
          this.addressData(),
          this.industryData(),
          this.welfareLabelBasicsData(),
          this.expectedSalaryData(),
      ]);

      if(this.$route.query.id){
        await this.initData();
    }

  },
  methods: {
      handleChange(value) {
          // this.jobForm.positionId=value[value.length-1];
          console.log(value+"99999");
      },
      //   获取省数组
      async addressData(){
          const res=await this.$axios.request({
              url:"/web/recruitmentPost/provinceList",
              method:"get",
          })
          console.log(res.data+"+++++");
          if (res.data.msg==="success"){
              // this.addressList=res.data;
              this.provinces=res.data.provinceList;
          }
      },
      async provinceChange(id){
          const result=await this.$axios.request({
              url:"/web/recruitmentPost/cityList",
              method:"get",
              params: {
                  provinceId:id,
              }
          })
          if(result.data.msg==="success"){
              this.citis=result.data.cityList;
              this.jobForm.city.id='';
              this.jobForm.address.id='';
              this.areaList=[];
              // this.cityChange(this.jobForm.city.id)
          }
      },
      async getCityList(id){
          const result=await this.$axios.request({
              url:"/web/recruitmentPost/cityList",
              method:"get",
              params: {
                  provinceId:id,
              }
          })

          if(result.data.msg==="success"){
              this.citis=result.data.cityList;

          }
      },
      async cityChange(id){
          const result=await this.$axios.request({
              url:"/web/recruitmentPost/cityList",
              method:"get",
              params: {
                  provinceId:id,
              }
          })
          if(result.data.msg==="success"){
              this.areaList=result.data.cityList;
              this.jobForm.address.id='';
          }
      },
      async getAreaList(id){
          const result=await this.$axios.request({
              url:"/web/recruitmentPost/areaList",
              method:"get",
              params: {
                  cityId:id,
              }
          })

          if(result.data.msg==="success"){
              this.areaList=result.data.areaList;

          }
      },
    // 如果是职位编辑情况下，路由会带职位ID参数,请求后台数据赋值
    async initData() {
      const res = await this.$axios.request({
        url: "/web/recruitmentPost/selectById",
        method: "get",
        params:{
            id: this.$route.query.id,
        },
      })
      console.log(res.data+"ppp");
      if(res.data.msg === "success") {
        this.jobForm = res.data.recruitmentPost;
        this.value=[this.jobForm.industry.id,this.jobForm.positionType.id,this.jobForm.position.id];
        this.getCityList(this.jobForm.province.id)
        this.getAreaList(this.jobForm.city.id)

        // this.checkList=this.jobForm.jobWelfareLabelBasicsList
        // this.checkList = this.jobForm.jobWelfareLabelBasicsList.map(item => item.welfareLabelBasics);
        //   this.checkList = this.checkList.filter(item => item !== undefined && item !== null);
        // this.checkList = this.checkList.map(item => item.title);
        //   console.log(this.checkList+")))))")

        // 刷新key，引起子组件刷新及时更新prop
        this.key += 1;
      }
    },
   //   获取薪资待遇数组
   async expectedSalaryData(){
        const res=await this.$axios.request({
            url:"/web/recruitmentPost/expectedSalaryList",
            method:"get",
        })
       console.log("=========================================")
       console.log(res.data);
        if(res.data.msg==="success"){
            this.expectedSalaryList=res.data.expectedSalaryList;
        }
   },
      //   获取基础职位福利标签
      async welfareLabelBasicsData(){
          const res=await this.$axios.request({
              url:"/web/recruitmentPost/welfareLabelBasicsList",
              method:"get",
          })
          console.log("=========================================")
          console.log(res.data);
          if(res.data.msg==="success") {
              this.welfareLabelBasicsList = res.data.welfareLabelBasicsList;
          }
      },
   //   获取行业数组
   async industryData(){
        const res=await this.$axios.request({
            url:"/web/recruitmentPost/industryList",
            method:"get",
        })
       console.log(res.data.industryList+"--)))");
        if (res.data.msg==="success"){
            this.industryList=res.data.industryList;
            this.options=this.industryList.map(({id,title,positionTypeList}) =>({
                value:id,
                label:title,
                children:positionTypeList.map(({id,title,positionList}) =>({
                    value:id,
                    label:title,
                    children:positionList.map(({id,title})=>({
                        value:id,
                        label:title
                    }))
                }))
            }))
        }
   },

      //获取经验时长
      async workExperienceData(){
          const res=await this.$axios.request({
              url:"/web/recruitmentPost/workExperienceList",
              method:"get",
          })
          console.log(res+"------");
          if (res.data.msg==="success"){
              this.workExperienceList=res.data.workExperienceList;
          }
      },
      //获取学历列表
      async recruitmentEducationData(){
          const res=await this.$axios.request({
              url:"/web/recruitmentPost/recruitmentEducationList",
              method:"get",
          })
          console.log(res+"------");
          if (res.data.msg==="success"){
              this.recruitmentEducationList=res.data.recruitmentEducationList;
          }
      },
      //获取工作类型列表
      async natureWorkData(){
          const res=await this.$axios.request({
              url:"/web/recruitmentPost/natureWorkList",
              method:"get",
          })
          console.log(res.data.natureWorkList[0].title+"000");
          if (res.data.msg==="success"){
              this.natureWorkList=res.data.natureWorkList;
          }
      },
    // // 薪酬转换
    // editJobSalary() {
    //   let baseSalary = "";
    //   if (this.min_salary && this.max_salary) {
    //     baseSalary = `${this.min_salary}-${this.max_salary}K`;
    //   }
    //   if (baseSalary && this.extra_salary) {
    //     baseSalary += `·${this.extra_salary}薪`
    //   }
    //   this.jobForm.job_salary = baseSalary;
    // },
    // jobSalaryReverse() {
    //   const salary = this.jobForm.job_salary.match(/\d+/g);
    //   this.min_salary =  salary[0];
    //   this.max_salary =  salary[1];
    //   if(salary.length === 3) {
    //     this.extra_salary =  salary[2];
    //   }
    // },
    // 预览时需要数据库职位表有该条记录（新增），所以预览结束后需要删除表中该条记录
    async previewOver(value) {
      this.previewVisible = value;
      const res = await this.$axios.request({
        url: `/job/delete`,
        method: "delete",
        data: {
          idArray: [this.jobForm.job_id],
        }
      });
      console.log(res);
    },
    // 提交表单
    submitForm(formName, job_status, isPreview = false) {
        console.log(this.jobForm.jobWelfareLabelBasicsTitles+"++++++")
      // 手动赋予职位标签，职位状态
      // this.$set(this.jobForm, "job_tag", this.tagTransform);
      // this.$set(this.jobForm, "job_status", job_status);
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$axios.request({
            url: "/web/recruitmentPost/saveOrUpdate?type="+job_status+"&checkList="+this.checkList+",",
            method: "post",
            data: this.jobForm,

          })
          console.log(res);
          if (res.data.msg === "success") {
            // 如果是职位新增，job_id为空，需要查库赋值
            if(!this.jobForm.id) {
              await this.$set(this.jobForm, "id", res.data.id);
            }
            // 预览简历将直接返回，不会有提示消息
            if (isPreview) {
              return this.previewVisible = isPreview;
            }

            this.$message.success("职位编辑成功");
            // this.resetForm(formName);
             await this.$router.push("/recruiter");
          } else {
            this.$message.error("职位编辑失败，请检查所提交的信息！");
          }
        } else {
          this.$message.error("提交信息有误，请重新确认!");
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
}
</script>

<style lang="less" scoped>

@mainColor: #5dd5c8;
@activeColor: #00c2b3;
@background: #fff;
@fontColor: #414a60;
@salaryColor: #fb670f;
@promptColor: #8d92a1;
@borderColor: #dcdfe6;
main {
  margin-top: 30px;

  > div {
    background: @background;

  }

  .main-header {
    border-bottom: 1px solid @borderColor;

    .el-page-header {
      padding-left: 30px;
      height: 80px;
      line-height: 80px;

      /deep/ .el-page-header__left {
        .el-icon-back,
        .el-page-header__title {
          color: @fontColor;
          font-size: 22px;
        }
      }

      /deep/ .el-page-header__content {
        color: @activeColor;
        font-size: 22px;
      }
    }
  }

  .main-content {
    padding: 0 10%;

    .post-wrapper {
      padding: 30px 0;
      border-bottom: 1px solid @borderColor;

      &:last-of-type {
        border-bottom: 0;
      }

      h2 {
        margin: 30px 0 60px;
      }

      .content {
        .el-form-item.left-form-item {
          padding-right: 15px;
          width: 40%;
        }

        .el-form-item.right-form-item {
          padding-left: 15px;
          width: 60%;
        }

        .el-form-item {
          width: 100%;

          /deep/ .el-form-item__label {
            color: @fontColor;
            font-size: 16px;
          }

          /deep/ .el-form-item__content {
            &::before {
              content: "";
              clear: both;
              display: table;
                width: 300px;
            }
          }

          .el-select {
            width: 100%;
          }

          &:not(.edit-btn) {
            display: inline-block;
          }

          .el-input-number {
            width: 150px;

            /deep/ .el-input__inner {
              padding: 0 40px;
            }
          }
        }
      }
    }

    .handle-btn {
      height: 160px;
      line-height: 160px;
      display: flex;
      align-items: center;

      .preview-btn {
        margin-left: auto;
      }

      .preview-btn, .add-btn {
        height: 50px;
        line-height: 50px;
        width: 140px;
      }
    }
  }
}
</style>